<template>
	<view class="login-container">
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<button type="primary" class="btn-login" open-type="getUserInfo"  @getuserinfo="getuserinfo">一键登录</button>
		<view class="tips-text">登录后尽享更多权益</view>
	</view>
</template>

<script>
	import {mapState,mapMutations} from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				
			};
		},
		computed:{
			...mapState('m_user',['redirectInfo'])
		},
		methods:{
			// 用户授权之后，获取用户的基本信息
            ...mapMutations('m_user',['updateUserInfo','updateToken','updateRedirectInfo']),
			// 获取用户信息
			getuserinfo(e){
				if(e.detail.errMsg == 'errMsg: "fail auth deny') return uni.$showMsg('您取消了登录授权！')
				this.updateUserInfo(e.detail.userInfo)
				
				this.getToken(e.detail)
	
			},
			
			async getToken(info){
				// 获取code对应的值
				const res = await uni.login().catch(err => err)
				if(res.errMsg || res.errMsg !== "login:ok")  return uni.$showMsg('登录失败！')
				
				// 准备参数
				 const query = {
				    code: res.code,
				    encryptedData: info.encryptedData,
				    iv: info.iv,
				    rawData: info.rawData,
				    signature: info.signature
				  }
				  const loginResult =  await uni.$http.post('/api/public/v1/users/wxlogin',query)
				  if(loginResult.meat.status !== 200)  return uni.$showMsg('登录失败！')
				 
				 // 直接把token保存到 vuex 中
				 this.updateToken(loginResult.message.token)
				 
				  // 判断 vuex 中的 redirectInfo 是否为 null
				   // 如果不为 null，则登录成功之后，需要重新导航到对应的页面
				 this.navigateBack()
			},
			navigateBack(){
				if(this.redirectInfo && this.redirectInfo.openType == 'switchTab'){
					uni.switchTab({
						url:this.redirectInfo.from,
						complete:() => {
							this.updateRedirectInfo(null)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
.login-container{
	height:750rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #F8F8F8;
	position: relative;
	overflow: hidden;
	
	// 绘制登录盒子底部的半椭圆造型
	&::after{
		content: '';
		display: block;
		width:100%;
		height: 40px;
		background-color: white;
		position: absolute;
		bottom:0;
		left:0;
		border-radius: 100%;
		// 向下移自身高度的50%
		transform: translateY(50%);  
		
	}
	
	.btn-login{
		width: 90%;
		border-radius: 100rpx;
		margin: 15px 0;
		background-color: #C00000;
		
	}
	.tips-text{
		font-size: 12px;
		color:gray;
	}
}
</style>